package com.xu.cloud.common.filter;

import com.xu.cloud.common.constant.HttpConstant;
import com.xu.cloud.common.constant.LogConstant;
import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.trace.TraceIdHelper;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * @author xuguan
 * @since 2025/1/8
 */
@Order(value = OrderConstant.HTTP_HEADERS_SETTING_FILTER_ORDER)
@WebFilter(description = "HTTP请求头设置过滤器", urlPatterns = "/*")
public class HttpHeadersSettingFilter extends BaseRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader(HttpHeaders.CONTENT_ENCODING, StandardCharsets.UTF_8.name());
        response.setHeader(HttpHeaders.DATE, DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z")
                .withLocale(Locale.US).withZone(ZoneId.of("GMT+8"))
                .format(LocalDateTime.now()));

        // 添加traceId响应头
        response.addHeader(HttpConstant.HEADER_TRACE_ID, TraceIdHelper.getTraceId());

        filterChain.doFilter(request, response);
    }
}
